import 'dart:io';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_doc_scanner/flutter_doc_scanner.dart';

class WJScannerLogic extends GetxController {
  RxList<String> scannedPaths = <String>[].obs;
  RxBool isScanning = false.obs;
  RxString errorMessage = ''.obs;

  // 扫描文档并返回图像路径
  Future<void> scanDocuments({int pageCount = 4}) async {
    try {
      isScanning.value = true;
      errorMessage.value = '';

      // 使用官方 API
      final result = await FlutterDocScanner().getScanDocuments(page: pageCount);

      if (result != null && result.isNotEmpty) {
        scannedPaths.value = List<String>.from(result);
        Get.snackbar('成功', '扫描完成: ${scannedPaths.length} 页',
            backgroundColor: Colors.green);
      } else {
        errorMessage.value = '未获取到扫描结果';
      }
    } catch (e) {
      errorMessage.value = '扫描失败: $e';
      Get.snackbar('错误', errorMessage.value, backgroundColor: Colors.red);
    } finally {
      isScanning.value = false;
    }
  }

  // 扫描并生成 PDF
  Future<void> scanToPdf({int pageCount = 4}) async {
    try {
      isScanning.value = true;
      errorMessage.value = '';

      final pdfPath = await FlutterDocScanner().getScannedDocumentAsPdf(page: pageCount);

      if (pdfPath != null) {
        scannedPaths.value = [pdfPath]; // 保存 PDF 路径
        Get.snackbar('成功', 'PDF 已保存: $pdfPath',
            backgroundColor: Colors.green);
      } else {
        errorMessage.value = 'PDF 生成失败';
      }
    } catch (e) {
      errorMessage.value = '生成 PDF 失败: $e';
      Get.snackbar('错误', errorMessage.value, backgroundColor: Colors.red);
    } finally {
      isScanning.value = false;
    }
  }
}